package org.queryexecutor.database;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;

public class DatabaseConnection
{
	private static DatabaseConnection dbConnection;
	private static Connection connection;
	private static HashMap<String, Class<?>> sqlTypes;
	
	private DatabaseConnection()
	{
		sqlTypes = new HashMap<String, Class<?>>();
	}
	
	public static DatabaseConnection getInstance()
	{
		if(dbConnection == null){
			dbConnection = new DatabaseConnection();
		}
		return dbConnection;
	}
	
	public void addDriver(String driver) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		DriverManager.registerDriver((Driver) Class.forName(driver).newInstance());
	}
	
	public boolean connect(String connectionString, String user, String password) throws SQLException
	{
		if(user == null){
			connection = DriverManager.getConnection(connectionString);
		}else if(user != null && password != null){
			connection = DriverManager.getConnection(connectionString, user, password);
		}
		if(connection != null){
			return true;
		}
		return false;
	}
	
	public void mapSqlTypes()
	{
		sqlTypes.put("varchar", String.class);
		sqlTypes.put("char", String.class);
		sqlTypes.put("int", int.class);
		sqlTypes.put("double", double.class);
	}
	
	public Connection getConnection()
	{
		return connection;
	}
}
